require 'digest/sha2'

class User < ActiveRecord::Base  
  has_many :borrow_items, :dependent => :destroy  
  has_many :category_items, :dependent => :destroy 
  
  validates :name, :presence => true, :uniqueness => true, :length => {:minimum => 6, :maximum => 10} 
  validates :email, :presence => true, :uniqueness => true
 
  validates :password, :confirmation => true
  validates :full_name, :presence => true
  validates :password, :presence => true,  :length => {:minimum => 6, :maximum => 10} ,:on => :create
 
  attr_accessor :password_confirmation
  attr_reader   :password
  
  validates_format_of :email,
                      :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                      :message => "Invalid email"

  validate  :password_must_be_present
  
  before_create { generate_token(:auth_token) }

  def send_password_reset
    generate_token(:password_reset_token)
    self.password_reset_sent_at = Time.zone.now
    self.save!    
    UserMailer.password_reset(self).deliver
  end

  def generate_token(column)
    begin
      self[column] = SecureRandom.urlsafe_base64
    end while User.exists?(column => self[column])
  end
  
  def User.authenticate(name, password)
    if user = find_by_name(name)
      if user.hashed_password == encrypt_password(password, user.salt)
        user
      end
    end
  end

  def User.encrypt_password(password, salt)
    Digest::SHA2.hexdigest(password + "wibble" + salt)
  end
  
  # 'password' is a virtual attribute
  def password=(password)
    @password = password

    if password.present?
      generate_salt
      self.hashed_password = self.class.encrypt_password(password, salt)
    end
  end
  
  private

    def password_must_be_present
      errors.add(:password, "Missing password") unless hashed_password.present?
    end
  
    def generate_salt
      self.salt = self.object_id.to_s + rand.to_s
    end
end